package services

import (
	"fmt"
	"net/url"

	"boomlive.com/boomlive-common/configs"
	"boomlive.com/boomlive-common/utils"
	"github.com/beego/beego/v2/core/logs"
)

type UserBaseInfo struct {
	PhotoNum     string `json:"photo_num" mapstructure:"photo_num" db:"photo_num"`
	NickNm       string `json:"nick_nm" mapstructure:"nick_nm" db:"nick_nm"`
	UserSex      bool   `json:"user_sex" mapstructure:"user_sex" db:"user_sex"`
	UserInterest int    `json:"-" mapstructure:"user_interest" db:"user_interest"`
}

// 获取用户信息
func GetUserInfo(userId int64) (info UserBaseInfo, err error) {
	// 从已注册的数据库中取出连接（别名就是你配置中的 Alias）
	dbClient, err := utils.GetDB(configs.UnicomDBAliasName) // Phonecast 为配置中的 cfg.Alias
	if err != nil {
		return
	}

	// SQL Server 存储过程调用语法
	query := fmt.Sprintf("EXEC pr_getUserBaseInfo %d", userId)

	// 执行存储过程并将结果绑定到结构体
	err = dbClient.Get(&info, query)
	if err != nil {
		logs.Error("查询用户信息失败: %v", err)
		return
	}

	// 昵称解码处理
	if info.NickNm != "" {
		decoded, decErr := url.QueryUnescape(info.NickNm)
		if decErr != nil {
			logs.Error("昵称解码失败: %v", decErr)
			return info, decErr
		} else {
			info.NickNm = decoded
		}
	}

	return info, nil
}

func GetUserBalance(userId int64) (balance int64, err error) {
	dbClient, err := utils.GetDB("coin") // 使用新配置 alias
	if err != nil {
		logs.Error("获取 coin 数据库失败: %v", err)
		return 0, err
	}

	query := fmt.Sprintf("EXEC pr_getUserBalance %d", userId)

	var result struct {
		Balance int64 `db:"balance"`
	}
	err = dbClient.Get(&result, query)
	if err != nil {
		logs.Error("查询用户余额失败: %v", err)
		return 0, err
	}

	return result.Balance, nil
}
